const { DataTypes } = require('sequelize');
const { sequelize } = require('../config/database');

const LessonView = sequelize.define('LessonView', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '学生ID'
  },
  course_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '课程ID'
  },
  lesson_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '课时ID'
  },
  watch_time: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: '观看时长(秒)'
  },
  progress: {
    type: DataTypes.DECIMAL(5, 2),
    defaultValue: 0,
    comment: '观看进度(百分比)'
  },
  is_completed: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    comment: '是否完成'
  },
  last_position: {
    type: DataTypes.INTEGER,
    defaultValue: 0,
    comment: '最后观看位置(秒)'
  },
  watch_count: {
    type: DataTypes.INTEGER,
    defaultValue: 1,
    comment: '观看次数'
  },
  first_watch_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    comment: '首次观看时间'
  },
  last_watch_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    comment: '最后观看时间'
  },
  created_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    comment: '创建时间'
  },
  updated_at: {
    type: DataTypes.DATE,
    defaultValue: DataTypes.NOW,
    comment: '更新时间'
  }
}, {
  tableName: 'lesson_views',
  timestamps: true,
  createdAt: 'created_at',
  updatedAt: 'updated_at',
  indexes: [
    {
      fields: ['user_id']
    },
    {
      fields: ['course_id']
    },
    {
      fields: ['lesson_id']
    },
    {
      fields: ['user_id', 'lesson_id'],
      unique: true
    },
    {
      fields: ['last_watch_at']
    }
  ]
});

// 定义关联关系
LessonView.associate = (models) => {
  LessonView.belongsTo(models.User, {
    foreignKey: 'user_id',
    as: 'user'
  });
  
  LessonView.belongsTo(models.Course, {
    foreignKey: 'course_id',
    as: 'course'
  });
  
  LessonView.belongsTo(models.Lesson, {
    foreignKey: 'lesson_id',
    as: 'lesson'
  });
};

module.exports = LessonView; 